<?php

namespace App\Models;

use App\Constant\AliPay;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use ModStart\Core\Util\EncodeUtil;

class Order extends Model
{
    protected $table = "orders";

    public function order_dollarcoin()
    {
        return $this->hasMany(OrderDollarCoin::class, 'order_id', 'id');
    }
    
    
    public function add($data)
    {
        try {
            DB::beginTransaction();
            //1转入,2转出,3兑换
            if($data['add_type'] == 1){ //转入
                if($data['e_blog_id'] != 1 ){
                    return "转入账户只能是人民币账户";
                }
                $this->remark = "转入账户人民币";
            }else if($data['add_type'] == 2){  //转出
                if($data['s_blog_id'] != 1 ){
                    return "转出账户只能是人民币账户";
                }
                //查询账号金额
                $start = (new Bindwallet())->where(['blog_id'=>$data['s_blog_id'],"user_id"=>$data['user_id']])->first();
                if($start->rmb_price < $data['money'] ){
                    return "您的账户余额不足";
                }
                $this->remark = "将人民币转出账户";
            }else if($data['add_type'] == 3){  //兑换
                $start_blog = (new Blog())->where(['id'=>$data['s_blog_id']])->first();
                $end_blog = (new Blog())->where(['id'=>$data['e_blog_id']])->first();
                if(!$start_blog){
                    return "兑换货币已被删除,不能兑换！";
                }
                if (!$end_blog) {
                    return "被兑换货币已被删除,不能兑换！!";
                }
                //查询账号金额
                $start_account = (new Bindwallet())->where(['blog_id'=>$data['s_blog_id'],"user_id"=>$data['user_id']])->first();
                $end_account = (new Bindwallet())->where(['blog_id'=>$data['e_blog_id'],"user_id"=>$data['user_id']])->first();
                if(!$start_account){
                    return "兑换账户不存在！";
                }
                if (!$end_account) {
                    return "收款账户不存在!";
                }
                //查询龙币今天价格
                // 获取今天的日期
                $today = Carbon::today();
                // 查询小于今天的数据
                $results = SilverDollarCoin::whereDate('date_time', '<=', $today)->orderBy("date_time","desc")->first();
                if(!$results){
                    return "暂未获取到龙币价格";
                }
                //获取龙币总价格
                $data['total_price'] = $results->price * $data['number'];
//                if($start_account->rmb_price < $data['money'] ){
//                    return "您的账户余额不足";
//                }
                if($data['s_blog_id'] ==2){ //使用龙币兑换其他币
                    //判断账户龙币个数
                    $user_dollar_num = (new Bindwallet())->where(["blog_id"=>$data['s_blog_id'],"user_id"=>$data['user_id']])->first();
                    if($user_dollar_num->rmb_price < $data['number']){
                        return  "您的账号龙币数不足";
                    }
                   $exchangerates =  DB::table("exchangerates")->where(["blog_id"=>$data['s_blog_id'],"ex_blog_id"=>$data['e_blog_id']])->first();
                   if(empty($exchangerates)){
                       return  "暂未设置该货币的兑换汇率,不支持兑换!";
                   }
                    if($exchangerates){
//                       $data['plan_money'] = round($data['total_price'] * $exchangerates->ex_rates);
                       $data['money'] = number_format($data['total_price'] * $exchangerates->ex_rates, 2);//round($data['total_price'] * $exchangerates->ex_rates);
                       $this->dollar_coin_num = $data['number'];
                       $this->dollar_coin_price = $results->price;
                       $this->remark = "龙币兑换".$end_blog->title."币";
                   }
                }else if($data['s_blog_id'] ==1) { //使用人民币兑换龙币
                    if($data['e_blog_id'] != 2){
                        return "人民币只能兑换龙币!";
                    }
                    //查询人民币金额是否足够
                    $rmb_num = (new Bindwallet())->where(['user_id'=>$data['user_id'],'blog_id'=>1])->first();
                    //人民币需要多付总价的0.05
                    $more_out =  $data['total_price'] * 0.05;
                    $data['total_price'] = $data['total_price'] + $more_out;//总价
                    if($rmb_num->rmb_price < $data['total_price']){
                        return "人民币余额不足,请先充值!";
                    }
//                    $data['plan_money'] = $data['total_price'];
                    $data['money'] = $data['total_price'];//$data['number']; //round($data['money'] -  $data['money'] * 0.05);
                    $this->dollar_coin_num = $data['number'];
                    $this->dollar_coin_price = $results->price;
                    $this->remark = "人民币兑换龙币";
                }
            }
            if($data['money'] <=0){
                return "兑换金额太小,不能兑换!";
            }
            $info = DB::table("member_user")->where(['id'=>$data['user_id']])->first();
            if ($data['add_type'] != 1) {
                if (!$info->pay_pass) {
                    return "请先设置支付密码!";
                }
                $pass = EncodeUtil::md5WithSalt($data['password'], $info->passwordSalt);
                if ($pass != $info->pay_pass) {
                    return "您输入的密码不正确!";
                }
            }
            if ($data['add_type'] == 2) { //提现
                if (empty($info->ali_account) || empty($info->ali_name)) {
                    return "您还没有绑定支付宝账号,请先绑定后再提现!";
                }
            }
            $this->user_id = $data['user_id'];
            $this->sn = date('YmdHis') . mt_rand(1000, 9999);
            $this->money = $data['money'];
            $this->s_blog_id = isset($data['s_blog_id']) ? $data['s_blog_id'] : 0;
            $this->e_blog_id = isset($data['e_blog_id']) ? $data['e_blog_id'] : 0;;
//            $this->pay_type = $data['pay_type'];
            $this->add_type = $data['add_type'];
            //回调修改
//            $this->pay_status = 1;
//            $this->order_status = 1;
//            $this->pay_time = date("Y-m-d H::i:s",time());

            $result = $this->save();
            if ($result) {
                $lit = $this->giveMoneyToCard($data,$info);
            }
            if ($lit && $result) {
                DB::commit();
                if($data['add_type'] ==1){
                    return ['order_id'=>$this->id];
                }elseif ($data['add_type'] ==2){ //提现
                    //修改订单状态
                    (new Order())->where(['id'=>$this->id])->update(['pay_status'=>1,'order_status'=>1,'pay_time'=>date("Y-m-d H::i:s",time()),'pay_type'=>3]);
                }elseif ($data['add_type'] ==3){
                    if ($data['s_blog_id'] == 1 && $data['e_blog_id'] == 2) { //更新购买龙币状态
                        $coin_list = (new OrderDollarCoin())->where(['order_id' => $this->id])->get();
                        foreach ($coin_list as $item) {
                            $o_coin = new OrderDollarCoin();
                            $coin = new Goldcoins();
                            $o_coin->where(['id' => $item->id])->update(['is_pay' => 1]);
                            $coin->where(['id' => $item->dollar_coin_id])->update(['sale_state' => 1]);
                        }
                    }
                    //修改订单状态
                    (new Order())->where(['id'=>$this->id])->update(['pay_status'=>1,'order_status'=>1,'pay_time'=>date("Y-m-d H::i:s",time()),'pay_type'=>3]);
                }
                return true;
            } else {
                if ($data['add_type'] == 2) {
                    return "转出失败,请检查绑定支付宝账户是否正确或商户余额不足,请稍后再试!";
                }
                if ($data['add_type'] == 3) {
                    if ($data['s_blog_id'] == 1 && $data['e_blog_id'] == 2) {
                        return "龙币数量不足!";
                    }
                }
                return "操作失败!";
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /***
     * @param $data
     * @return bool
     * 回调处理金额
     */
    public function giveMoneyToCard($data,$info)
    {
        if ($data['add_type'] == 1) { //转入
           return true; //回调处理
//            $res =  (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['e_blog_id']])->increment("rmb_price", $data['money']);
//            if ($res) {
//                return true;
//            }
        } elseif ($data['add_type'] == 2) { //转出
            //支付宝提现之后再执行改操作
            //执行提现
            $lt['alipay_name'] = $info->ali_name;
            $lt['alipay_account'] = $info->ali_account;
            $lt['money'] = $data['money'];
            $aly_res = AliPay::withdrawal($lt);
            if($aly_res == 1){
                $res = (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['s_blog_id']])->decrement("rmb_price", $data['money']);
                if ($res) {
                    return true;
                }
            }
            return false;
        } elseif ($data['add_type'] == 3) { //兑换
            if($data['s_blog_id'] == 1 && $data['e_blog_id'] == 2){ //判断是人民币兑换龙币
                //分配龙币序号
               $logs =  $this->setDollarCoinSerialNumber($data);
               if($logs === true){
                   $start = (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['s_blog_id']])->decrement("rmb_price", $data['money']);
                   $end = (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['e_blog_id']])->increment("rmb_price", $data['number']);
                   if ($start && $end) {
                       return true;
                   }
               }
               return false;
//            }elseif ($data['s_blog_id'] == 2 && $data['s_blog_id'] == 1){ //判断是龙币兑换人民币
            } else { //龙币兑换其他
                //修改哪些龙币被兑换
                $set_log = $this->updateDollarCoinChangge($data);
                if ($set_log === true) {
                    $start = (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['s_blog_id']])->decrement("rmb_price", $data['number']);
                    $end = (new Bindwallet())->where(["user_id" => $data['user_id'], 'blog_id' => $data['e_blog_id']])->increment("rmb_price", $data['money']);
                    if ($start && $end) {
                        return true;
                    }
                }
            }
            return false;
        }
        return false;
    }


    /***
     * @param $data
     * 修改哪些龙币被交换
     */
    public function updateDollarCoinChangge($data)
    {
        $isable_list = (new OrderDollarCoin())->where(['user_id'=>$data['user_id'],'is_pay'=>1,'is_change'=>0])->limit($data['number'])->get();
        if(count($isable_list) < $data['number']){
            return "龙币数量不足,不能兑换";
        }
        foreach($isable_list as $item){
            (new OrderDollarCoin())->where(['id'=>$item->id])->update(['is_change'=>1]);
        }
        return true;
    }

    /***
    购买龙币,记录订单龙币
    */
    public function setDollarCoinSerialNumber($data)
    {
//        $count = (new Goldcoins())->where(['sale_state'=>0])->whereNotIn('id', function($query) {
//            $query->select('id')->from('order_dollar_coin');
//        })->count();
        $lit = (new Goldcoins())->where(['sale_state'=>0])->whereNotIn('id', function($query) {
            $query->select('dollar_coin_id')->from('order_dollar_coin');
        })->orderBy(\DB::raw('RAND()'))->limit($data['number'])->get();
        $count = count($lit);
        if($count < $data['number']){
            return "龙币数量不足!";
        }
        foreach($lit as $v){
            $order_dollar_coin_log = new OrderDollarCoin();
            $order_dollar_coin_log->user_id = $data['user_id'];
            $order_dollar_coin_log->dollar_coin_id = $v->id;
            $order_dollar_coin_log->order_id = $this->id;
            $order_dollar_coin_log->save();
        }
        return  true;
    }

    /**
     * @param $id
     * @return mixed
     * 获取订单信息
     */
    public static function getOrderInfo($id)
    {
        return self::where(['id'=>$id])->first();
    }

    /***
     * 获取用户购买龙币列表
     */
    public static function getOrderDragonList($data)
    {
        $o_list = self::with(['order_dollarcoin'])->where(['user_id' => $data['user_id'], 'add_type' => 3, 's_blog_id' => 1, 'e_blog_id' => 2,'order_status'=>1])->orderBy("id", "desc")->get();
        foreach ($o_list as $k => &$v) {
            foreach ($v->order_dollarcoin as $kk => &$vv) {
                $vv->info = Goldcoins::where(['id' => $vv->dollar_coin_id])->first();
            }
        }
        return $o_list;
    }

}
